package Controller

import (
	"encoding/json"
	"github.com/ahmetb/go-linq/v3"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/copier"
	"log"
	"math"
	"strconv"
	"time"
	"web_back_go/Common"
	"web_back_go/DAO/gorm"
	"web_back_go/DAO/gorm/GormModel"
	"web_back_go/Dto"
	"web_back_go/Response"
)

type prodTagReq struct {
	Id    int    `json:"id"`
	Title string `json:"title"`
	Seq   string `json:"seq"`
	Style string `json:"style"`
}

// ProdInfo 定义 ProdInfo 结构体在函数外
type ProdInfo struct {
	ProdId   int     `json:"prodId"`
	Pic      string  `json:"pic"`
	ProdName string  `json:"prodName"`
	Price    float64 `json:"price"`
	Brief    string  `json:"brief"`
	ShopName string  `json:"shopName"`
}

// TransportResult 定义用于接收查询结果的结构体
type TransportResult struct {
	TransportID      int64     `json:"transport_id"`
	TransName        string    `json:"trans_name"`
	CreateTime       time.Time `json:"create_time"`
	ShopID           int64     `json:"shop_id"`
	ChargeType       int8      `json:"charge_type"`
	IsFreeFee        int8      `json:"is_free_fee"`
	HasFreeCondition int8      `json:"has_free_condition"`

	TransfeeID      int64   `json:"transfee_id"`
	ContinuousPiece float64 `json:"continuous_piece"`
	FirstPiece      float64 `json:"first_piece"`
	ContinuousFee   float64 `json:"continuous_fee"`
	FirstFee        float64 `json:"first_fee"`

	TranscityID int64 `json:"transcity_id"`
	CityID      int64 `json:"city_id"`

	AreaID   int64  `json:"area_id"`
	AreaName string `json:"area_name"`
}

// TransportFreeResult 定义用于接收查询结果的结构体
type TransportFreeResult struct {
	TransfeeFreeID int64   `json:"transfee_free_id"`
	TransportID    int64   `json:"transport_id"`
	FreeType       int8    `json:"free_type"`
	Amount         float64 `json:"amount"`
	Piece          float64 `json:"piece"`

	TranscityFreeID int64 `json:"transcity_free_id"`
	FreeCityID      int64 `json:"free_city_id"`

	AreaID   int64  `json:"area_id"`
	AreaName string `json:"area_name"`
}

/*
GetProdTagList
@Description: 获取商品标签列表
@param c
@return
*/
func GetProdTagList(c *gin.Context) {
	var db = gorm.Db
	var prodTagList []GormModel.TzProdTag

	// 添加查询条件和排序
	result := db.Table("tz_prod_tag").
		Where("status = ?", 1).
		Order("seq DESC").
		Find(&prodTagList)

	if result.Error != nil {
		log.Println(result.Error)
		c.JSON(200, Response.ResponseBody{
			Code:    "A00001",
			Msg:     "服务器异常",
			Data:    nil,
			Version: "1.0.0",
		})
		return
	}

	var proTagReq []prodTagReq
	for _, prodTag := range prodTagList {
		proTagReq = append(proTagReq, prodTagReq{
			Id:    int(prodTag.ID),
			Title: *prodTag.Title,
			Seq:   strconv.Itoa(*prodTag.Seq), // 将 int 类型的 Seq 转换为 string
			Style: strconv.Itoa(*prodTag.Style),
		})
	}

	c.JSON(200, Response.ResponseBody{
		Code:      "00000",
		Data:      proTagReq,
		Msg:       "请求成功",
		Version:   "v1.0",
		Success:   true,
		Timestamp: time.Now().Unix(),
	})
}

/*
GetProdListByTagId
@Description: 根据标签id获取商品列表
@param c
@return
*/
func GetProdListByTagId(c *gin.Context) {
	tagId := c.Query("tagId")
	sizeStr := c.Query("size")
	var db = gorm.Db

	// 将 size 转换为 int 类型
	sizeInt, err := strconv.Atoi(sizeStr)
	if err != nil || sizeInt <= 0 {
		log.Println("Invalid size parameter:", err)
		c.JSON(200, Response.ResponseBody{
			Code:    "A00001",
			Msg:     "参数错误",
			Data:    nil,
			Version: "1.0.0",
		})
		return
	}

	// 将 tagId 转换为 int 类型
	tagIdInt, err := strconv.Atoi(tagId)
	if err != nil {
		log.Println("Invalid tagId parameter:", err)
		c.JSON(200, Response.ResponseBody{
			Code:    "A00001",
			Msg:     "参数错误",
			Data:    nil,
			Version: "1.0.0",
		})
		return
	}

	// 获取总记录数
	var total int64
	result := db.Raw(`
		SELECT COUNT(*)
		FROM tz_prod p
		LEFT JOIN tz_prod_tag_reference ptr ON ptr.prod_id = p.prod_id
		LEFT JOIN tz_prod_tag pt ON pt.id = ptr.tag_id
		WHERE pt.id = ? AND p.status = 1
	`, tagIdInt).Count(&total)

	if result.Error != nil {
		log.Println(result.Error)
		c.JSON(200, Response.ResponseBody{
			Code:    "A00001",
			Msg:     "服务器异常",
			Data:    nil,
			Version: "1.0.0",
		})
		return
	}

	// 计算总页数
	pages := 0

	pages = int((total + int64(sizeInt) - 1) / int64(sizeInt))

	var prodList []ProdInfo

	// 执行原生 SQL 查询
	result = db.Raw(`
		SELECT p.prod_id, p.pic, p.prod_name, p.price, p.brief, sd.`+"`shop_name`"+`
		FROM tz_prod p
		LEFT JOIN tz_prod_tag_reference ptr ON ptr.`+"`prod_id`"+` = p.`+"`prod_id`"+`
		LEFT JOIN tz_prod_tag pt ON pt.`+"`id`"+` = ptr.`+"`tag_id`"+`
		LEFT JOIN tz_shop_detail sd ON p.shop_id = sd.shop_id
		WHERE pt.`+"`id`"+` = ? AND p.status = 1
		ORDER BY p.`+"`update_time`"+` DESC
		LIMIT ?
	`, tagIdInt, sizeInt).Scan(&prodList)

	if result.Error != nil {
		log.Println(result.Error)
		c.JSON(200, Response.ResponseBody{
			Code:    "A00001",
			Msg:     "服务器异常",
			Data:    nil,
			Version: "1.0.0",
		})
		return
	}

	c.JSON(200, Response.ResponseBody{
		Code: "00000",
		Data: Common.PageParam1[ProdInfo]{
			Current: 1, // 默认当前页为1，如果需要支持多页，需从请求参数中获取
			Total:   total,
			Size:    sizeInt,
			Records: prodList,
			Pages:   pages,
		},
		Msg:       nil,
		Version:   "v1.0",
		Success:   true,
		Timestamp: time.Now().Unix(),
	})
}

/*
GetProdInfoById
@Description: 根据商品id获取商品信息
@param c
*/
func GetProdInfoById(c *gin.Context) {
	prodId := c.Query("prodId")
	var db = gorm.Db
	var prod GormModel.TzProd
	prodRes := db.Table("tz_prod").Where("prod_id = ?", prodId).Find(&prod)

	if prodRes.Error != nil || prodRes.RowsAffected == 0 {
		log.Println(prodRes.Error, prodRes.RowsAffected)
		c.JSON(200, Response.ResponseBody{
			Code:    "A00001",
			Msg:     "商品异常",
			Data:    nil,
			Version: "1.0.0",
			Success: false,
			Fail:    true,
		})
		return
	}

	// 获取商店信息
	var shopDetail GormModel.TzShopDetail
	db.Table("tz_shop_detail").Where("shop_id = ?", prod.ShopID).Find(&shopDetail)

	var skuList []GormModel.TzSku
	db.Table("tz_sku").Where("prod_id = ? and is_delete = 0", prodId).Find(&skuList)

	var useSkuList []GormModel.TzSku
	linq.From(skuList).WhereT(func(sku GormModel.TzSku) bool {
		return *sku.Status == 1
	}).ToSlice(&useSkuList)

	var deliveryMode Dto.DeliveryMode

	// 检查 prod.DeliveryMode 是否为有效的 JSONB
	if prod.DeliveryMode.Valid { // 先检查 Valid
		err := json.Unmarshal([]byte(prod.DeliveryMode.String), &deliveryMode)
		if err != nil {
			log.Println("Failed to decode DeliveryMode:", err)
			c.JSON(200, Response.ResponseBody{
				Code:    "A00001",
				Msg:     "服务器异常",
				Data:    nil,
				Version: "1.0.0",
				Success: false,
				Fail:    true,
			})
			return
		}
	} else {
		log.Println("DeliveryMode is nil or invalid")
	}

	var transport GormModel.TzTransport

	if deliveryMode.HasShopDelivery && prod.DeliveryTemplateID != nil {
		var transportResults []TransportResult
		db.Raw(`
			select port.transport_id, port.trans_name, port.create_time, port.shop_id, port.charge_type, port.is_free_fee, port.has_free_condition,
			       fee.transfee_id, fee.continuous_piece, fee.first_piece, fee.continuous_fee, fee.first_fee,
			       city.transcity_id, city.city_id,
			       ta.area_id, ta.area_name
			from tz_transport port
			left join tz_transfee fee on port.transport_id = fee.transport_id
			left join tz_transcity city on fee.transfee_id = city.transfee_id
			left join tz_area ta on city.city_id = ta.area_id
			where port.transport_id = ? order by fee.transfee_id;
		`, prod.DeliveryTemplateID).Scan(&transportResults)

		var transportFreeResults []TransportFreeResult
		db.Raw(`
			select feefree.transfee_free_id, feefree.transport_id, feefree.free_type, feefree.amount, feefree.piece,
			       cityfree.transcity_free_id, cityfree.free_city_id,
			       ta.area_id, ta.area_name
			from tz_transfee_free feefree
			left join tz_transcity_free cityfree on feefree.transfee_free_id = cityfree.transfee_free_id
			left join tz_area ta on cityfree.free_city_id = ta.area_id
			where feefree.transport_id = ? order by feefree.transfee_free_id;
		`, prod.DeliveryTemplateID).Scan(&transportFreeResults)

		// 构建 transport 结构体
		if len(transportResults) > 0 {
			transport.TransportID = transportResults[0].TransportID
			transport.TransName = transportResults[0].TransName
			transport.CreateTime = transportResults[0].CreateTime
			transport.ShopID = transportResults[0].ShopID
			transport.ChargeType = transportResults[0].ChargeType
			transport.IsFreeFee = transportResults[0].IsFreeFee
			transport.HasFreeCondition = transportResults[0].HasFreeCondition

			// 构建 transfees 和 transcities
			var transfeeMap = make(map[int64]GormModel.TzTransfee)
			for _, result := range transportResults {
				if transfee, exists := transfeeMap[result.TransfeeID]; exists {
					var transcity GormModel.TzTranscity
					_ = copier.Copy(&transcity, &result) // 使用 copier 复制字段
					transfee.Transcities = append(transfee.Transcities, transcity)
					transfeeMap[result.TransfeeID] = transfee
				} else {
					var transfee GormModel.TzTransfee
					_ = copier.Copy(&transfee, &result) // 使用 copier 复制字段

					var transcity GormModel.TzTranscity
					_ = copier.Copy(&transcity, &result) // 使用 copier 复制字段
					transfee.Transcities = append(transfee.Transcities, transcity)
					transfeeMap[result.TransfeeID] = transfee
				}
			}

			for _, transfee := range transfeeMap {
				// 确保 cityList 在为空时返回空数组
				if len(transfee.Transcities) == 0 || transfee.Transcities[0].TranscityID == 0 {
					transfee.Transcities = []GormModel.TzTranscity{}
				}
				transport.Transfees = append(transport.Transfees, transfee)
			}
		}

		// 构建 transfee_frees 和 transcity_frees
		var transfeeFreeMap = make(map[int64]GormModel.TzTransfeeFree)
		for _, result := range transportFreeResults {
			if transfeeFree, exists := transfeeFreeMap[result.TransfeeFreeID]; exists {
				var transcityFree GormModel.TzTranscityFree
				_ = copier.Copy(&transcityFree, &result) // 使用 copier 复制字段
				transfeeFree.TranscityFrees = append(transfeeFree.TranscityFrees, transcityFree)
				transfeeFreeMap[result.TransfeeFreeID] = transfeeFree
			} else {
				var transfeeFree GormModel.TzTransfeeFree
				_ = copier.Copy(&transfeeFree, &result) // 使用 copier 复制字段

				var transcityFree GormModel.TzTranscityFree
				_ = copier.Copy(&transcityFree, &result) // 使用 copier 复制字段
				transfeeFree.TranscityFrees = append(transfeeFree.TranscityFrees, transcityFree)
				transfeeFreeMap[result.TransfeeFreeID] = transfeeFree
			}
		}

		for _, transfeeFree := range transfeeFreeMap {
			transport.TransfeeFrees = append(transport.TransfeeFrees, transfeeFree)
		}

		// 确保 transfeeFrees 在为空时返回空数组
		if len(transport.TransfeeFrees) == 0 {
			transport.TransfeeFrees = []GormModel.TzTransfeeFree{}
		}

		//log.Println(transport)

		// 返回响应
		c.JSON(200, Response.ResponseBody{
			Code: "00000",
			Msg:  "请求成功",
			Data: map[string]interface{}{
				"shopId":      prod.ShopID,
				"shopName":    shopDetail.ShopName,
				"prodId":      prod.ProdID,
				"prodName":    prod.ProdName,
				"price":       prod.Price,
				"content":     prod.Content,
				"oriPrice":    prod.OriPrice,
				"totalStocks": prod.TotalStocks,
				"brief":       prod.Brief,
				//"pic":         "https://img.mall4j.com/" + *prod.Pic,
				//"imgs":        "https://img.mall4j.com/" + *prod.Imgs,
				"pic":        *prod.Pic,
				"imgs":       *prod.Imgs,
				"categoryId": prod.CategoryID,
				"skuList":    useSkuList,
				"transport":  transport,
			},
			Version:   "v1.0",
			Success:   true,
			Timestamp: time.Now().Unix(),
		})
	}
}

/*
GetTagProdList

	@Operation(summary = "首页所有标签商品接口" , description = "获取首页所有标签商品接口")
*/
func GetTagProdList(c *gin.Context) {
	var tagProductList []struct {
		ID       int64   `json:"id"`
		Title    string  `json:"title"`
		Seq      string  `json:"seq"`
		Style    string  `json:"style"`
		ProdId   int64   `json:"prod_id"`
		Pic      string  `json:"pic"`
		ProdName string  `json:"prod_name"`
		Price    float64 `json:"price"`
		Brief    string  `json:"brief"`
		ShopName string  `json:"shop_name"`
		ShopId   int64   `json:"shop_id"`
	}

	// 定义 SQL 查询
	sqlQuery := `
	SELECT pt.id AS tag_id,
	       pt.title,
	       pt.seq,
	       pt.style,
	       p.prod_id,
	       p.pic,
	       p.prod_name,
	       p.price,
	       p.brief,
	       sd.shop_name,
	       p.shop_id
	FROM tz_prod_tag pt
	LEFT JOIN
	(
	    SELECT ptr.* 
	    FROM tz_prod_tag_reference ptr
	    INNER JOIN tz_prod p3 ON p3.prod_id = ptr.prod_id AND p3.status = 1
	    WHERE
	    (SELECT COUNT(0) 
	     FROM tz_prod_tag_reference prt2
	     INNER JOIN tz_prod p2 ON p2.prod_id = prt2.prod_id AND p2.status = 1
	     WHERE prt2.tag_id = ptr.tag_id AND prt2.create_time > ptr.create_time) < 6
	    ORDER BY ptr.tag_id, ptr.create_time DESC
	) AS temp
	ON temp.tag_id = pt.id
	LEFT JOIN tz_prod p
	ON p.prod_id = temp.prod_id
	LEFT JOIN tz_shop_detail sd
	ON p.shop_id = sd.shop_id
	ORDER BY pt.seq DESC;
	`

	// 执行 SQL 查询并将结果扫描到 tagProductList 中
	result := gorm.Db.Raw(sqlQuery).Scan(&tagProductList)

	if result.Error != nil {
		c.JSON(500, Response.ResponseBody{
			Code:    "A00005",
			Msg:     "服务器出了点小差",
			Data:    nil,
			Sign:    nil,
			Success: false,
			Fail:    true,
		})
		return
	}

	// 处理结果，将商品信息分组到对应的标签下
	tagMap := make(map[int64]*Dto.TagProductDto)
	for _, item := range tagProductList {
		productDto := Dto.ProductDto{
			ShopId:   item.ShopId,
			ShopName: item.ShopName,
			ProdId:   item.ProdId,
			ProdName: item.ProdName,
			Price:    item.Price,
			Brief:    item.Brief,
			Pic:      item.Pic,
		}
		if tag, exists := tagMap[item.ID]; exists {
			tag.ProductDtoList = append(tag.ProductDtoList, productDto)
		} else {
			tagMap[item.ID] = &Dto.TagProductDto{
				ID:             item.ID,
				Title:          item.Title,
				Seq:            item.Seq,
				Style:          item.Style,
				ProductDtoList: []Dto.ProductDto{productDto},
			}
		}
	}

	// 将结果转换为切片
	var finalResult []Dto.TagProductDto
	for _, tag := range tagMap {
		finalResult = append(finalResult, *tag)
	}

	c.JSON(200, Response.ResponseBody{
		Code:    "00000",
		Data:    finalResult,
		Success: true,
		Msg:     "Success",
		Version: "1.0",
	})
}

type ProductWithDetails struct {
	ShopId     int64   `json:"shopId"`     // 店铺ID
	ShopName   string  `json:"shopName"`   // 店铺名称
	ProdId     int64   `json:"prodId"`     // 商品ID
	ProdName   string  `json:"prodName"`   // 商品名称
	Price      float64 `json:"price"`      // 商品价格
	Brief      string  `json:"brief"`      // 简要描述，卖点等
	Pic        string  `json:"pic"`        // 商品主图
	CategoryId int64   `json:"categoryId"` // 商品分类id
	Content    string  `json:"content"`    // 商品详情
}

/*
GetProdList
@Description: 通过分类id商品列表信息
*/
func GetProdList(c *gin.Context) {
	// 获取查询参数
	categoryIdStr := c.Query("categoryId")
	currentStr := c.Query("current")
	sizeStr := c.Query("size")

	// 初始化分页参数，默认值
	var categoryId int64 = 0
	var page, size int = 1, 10

	// 解析 categoryId 参数
	if categoryIdStr != "" {
		var err error
		categoryId, err = strconv.ParseInt(categoryIdStr, 10, 64)
		if err != nil {
			c.JSON(200, Response.ResponseBody{
				Code:    "A00001",
				Msg:     "参数错误",
				Success: false,
				Version: "1.0.0",
			})
			return
		}
	}

	// 解析当前页码参数
	if currentStr != "" {
		page, _ = strconv.Atoi(currentStr)
		if page < 1 {
			page = 1
		}
	}

	// 解析每页大小参数
	if sizeStr != "" {
		size, _ = strconv.Atoi(sizeStr)
		if size < 1 {
			size = 10
		}
	}

	// 初始化数据库连接
	db := gorm.Db

	// 构建 SQL 查询
	var sqlQuery string
	var args []interface{}

	sqlQuery = `
		SELECT tp.prod_id, tp.pic, tp.prod_name, tp.price, tp.brief, tp.content, tc.category_id, tsd.shop_name
		FROM tz_prod tp
		LEFT JOIN tz_shop_detail tsd ON tp.shop_id = tsd.shop_id
		LEFT JOIN tz_category tc ON tp.category_id = tc.category_id
		WHERE tp.status = ?
	`

	args = append(args, 1)

	if categoryId != 0 {
		sqlQuery += " AND tp.category_id = ?"
		args = append(args, categoryId)
	}

	sqlQuery += " ORDER BY tp.create_time DESC LIMIT ? OFFSET ?"
	args = append(args, size, (page-1)*size)

	// 执行 SQL 查询并将结果扫描到 prodList 中
	var prodList []ProductWithDetails
	result := db.Raw(sqlQuery, args...).Scan(&prodList)

	if result.Error != nil {
		log.Println("Error querying products:", result.Error)
		c.JSON(200, Response.ResponseBody{
			Code:    "A00001",
			Msg:     "服务器异常",
			Success: false,
			Version: "1.0.0",
		})
		return
	}

	// 计算总数
	var count int64
	countQuery := `
		SELECT COUNT(*)
		FROM tz_prod tp
		WHERE tp.status = ?
	`
	countArgs := []interface{}{1}

	if categoryId != 0 {
		countQuery += " AND tp.category_id = ?"
		countArgs = append(countArgs, categoryId)
	}

	if err := db.Raw(countQuery, countArgs...).Count(&count).Error; err != nil {
		log.Println("Error counting products:", err)
		c.JSON(200, Response.ResponseBody{
			Code:    "A00001",
			Msg:     "服务器异常",
			Success: false,
			Version: "1.0.0",
		})
		return
	}

	// 返回响应
	c.JSON(200, Response.ResponseBody{
		Code: "00000",
		Data: Common.PageParam1[ProductWithDetails]{
			Current: page,
			Total:   count,
			Size:    size,
			Records: prodList,
			Pages:   int(math.Ceil(float64(count) / float64(size))),
		},
		Success:   true,
		Msg:       "Success",
		Version:   "1.0",
		Timestamp: time.Now().Unix(),
	})
}

/*
MoreBuyProdList
@Description: 每日疯抢
*/
func MoreBuyProdList(c *gin.Context) {
	currentStr := c.Query("current")
	sizeStr := c.Query("size")

	var page, size = 1, 10

	// 解析当前页码参数
	if currentStr != "" {
		page, _ = strconv.Atoi(currentStr)
		if page < 1 {
			page = 1
		}
	}

	// 解析每页大小参数
	if sizeStr != "" {
		size, _ = strconv.Atoi(sizeStr)
		if size < 1 {
			size = 10
		}
	}
	db := gorm.Db
	var count int64
	/*
		SELECT
		    p.prod_id,
		    p.pic,
		    p.prod_name,
		    p.price,
		    p.brief,
		    sd.`shop_name`
		FROM tz_prod p
		         LEFT JOIN tz_shop_detail sd
		                   ON p.shop_id = sd.shop_id
		WHERE p.`status` = 1
		ORDER BY p.`sold_num` DESC, p.`update_time` DESC;
	*/

	var prodList []ProductWithDetails
	db.Raw(`
	SELECT
		p.prod_id,
		p.pic,
		p.prod_name,
		p.price,
		p.brief,
		sd.shop_name
	FROM tz_prod p
	LEFT JOIN tz_shop_detail sd ON p.shop_id = sd.shop_id
	WHERE p.status = 1
	ORDER BY p.sold_num DESC, p.update_time DESC
	LIMIT ? OFFSET ?
`, size, (page-1)*size).Scan(&prodList)
	db.Raw(`
	SELECT COUNT(*)
	FROM tz_prod p
	WHERE p.status = 1
	ORDER BY p.sold_num DESC, p.update_time DESC
`).Scan(&count)
	c.JSON(200, Response.ResponseBody{
		Code: "00000",
		Data: Common.PageParam1[ProductWithDetails]{
			Current: page,
			Total:   count,
			Size:    size,
			Records: prodList,
			Pages:   int(math.Ceil(float64(count) / float64(size))),
		},
		Success: true,
		Msg:     "Success",
		Version: "1.0",
	})
}

/*
GetLastedProdPage

	@Operation(summary = "新品推荐" , description = "获取新品推荐商品列表")
*/
func GetLastedProdPage(c *gin.Context) {
	// 获取查询参数

	currentStr := c.Query("current")
	sizeStr := c.Query("size")

	// 初始化分页参数，默认值
	var page, size int = 1, 10
	// 解析当前页码参数
	if currentStr != "" {
		page, _ = strconv.Atoi(currentStr)
		if page < 1 {
			page = 1
		}
	}

	// 解析每页大小参数
	if sizeStr != "" {
		size, _ = strconv.Atoi(sizeStr)
		if size < 1 {
			size = 10
		}
	}

	// 初始化数据库连接
	db := gorm.Db
	/*

		SELECT
		    p.prod_id,
		    p.pic,
		    p.prod_name,
		    p.price,
		    p.brief,
		    sd.`shop_name`
		FROM tz_prod p
		         LEFT JOIN tz_shop_detail sd
		                   ON p.shop_id = sd.shop_id
		WHERE `status` = 1
		ORDER BY putaway_time DESC;
	*/
	var prodList []ProductWithDetails
	db.Raw(`
	SELECT
		p.prod_id,
		p.pic,
		p.prod_name,
		p.price,
		p.brief,
		sd.shop_name
	FROM tz_prod p
	LEFT JOIN tz_shop_detail sd ON p.shop_id = sd.shop_id
	WHERE p.status = 1
	ORDER BY p.putaway_time DESC
	LIMIT ? OFFSET ?
`, size, (page-1)*size).Scan(&prodList)
	var count int64
	db.Raw(`
	SELECT COUNT(*)
	FROM tz_prod p
	WHERE p.status = 1
	ORDER BY p.putaway_time DESC
`).Scan(&count)
	c.JSON(200, Response.ResponseBody{
		Code: "00000",
		Data: Common.PageParam1[ProductWithDetails]{
			Current: page,
			Total:   count,
			Size:    size,
			Records: prodList,
			Pages:   int(math.Ceil(float64(count) / float64(size))),
		},
		Success: true,
		Msg:     nil,
		Version: "1.0",
	})
}
